package com.xbongbong.paas.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.CardListDTO;
import com.xbongbong.paas.pojo.dto.CardSaveDTO;
import com.xbongbong.paas.pojo.vo.CardListVO;
import com.xbongbong.paas.pojo.vo.CardSaveVO;
import com.xbongbong.paas.service.CustomCardService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/8/30 15:30
 * @desrcption: 自定义卡片
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/mobile/card")
public class CustomCardController {

    @Resource
    private CustomCardService customCardService;

    /**
     * 设置卡片
     * @param cardSaveDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String save(@RequestBody @Valid CardSaveDTO cardSaveDTO, BindingResult br) {
        XbbResponse<CardSaveVO> response;
        if(br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                CardSaveVO cardSaveVO = customCardService.save(cardSaveDTO);
                response = new XbbResponse<>(cardSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 卡片列表
     * @param cardListDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid CardListDTO cardListDTO, BindingResult br) {
        XbbResponse<CardListVO> response;
        if(br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                CardListVO cardListVO = customCardService.list(cardListDTO);
                response = new XbbResponse<>(cardListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
